﻿/*****************************************************************************
Copyright (c) 2011 SmartVault, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
******************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;

namespace SmartVault.Net
{
    /// <summary>
    /// MimeSectionWriter
    /// 
    /// Used to read mime sections from a multipart mime message.
    /// </summary>
    public class MultipartMimeReader
    {
        private Stream Stream { get; set; }
        private byte[] Boundary { get; set; }
        private byte[] LastBoundary { get; set; }
        private int Section { get; set; }
        private MemoryStream Region { get; set; }
        private MemoryStream Line { get; set; }
        private bool Last { get; set; }
        private int LineCount { get; set; }

        private void BuildBoundary(byte[] boundary, long length)
        {
            MemoryStream match = new MemoryStream();
            MemoryStream lastMatch = new MemoryStream();
            byte[] b = Constants.MimeBoundaryStartBinary;

            match.Write(boundary, 0, (int)length);

            lastMatch.Write(boundary, 0, (int)length);
            lastMatch.Write(b, 0, b.Length);

            this.Boundary = match.ToArray();
            this.LastBoundary = lastMatch.ToArray();
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="stream"></param>
        public MultipartMimeReader(Stream stream)
        {
            this.Stream = stream;
            this.Section = -1;
            this.Line = new MemoryStream();
            this.Region = new MemoryStream();
            this.LineCount = -1;
        }

        private bool IsMatch(byte[] lhs, long l1, byte[] rhs, long l2)
        {
            if (l1 != l2)
            {
                return false;
            }

            for (int i = 0; i < l1; ++i)
            {
                if (lhs[i] != rhs[i]) return false;
            }

            return true;
        }

        private bool IsBoundary()
        {
            byte[] buffer = this.Line.GetBuffer();
            long length = this.Line.Length;

            // we have not found the boundary yet
            if (this.Boundary == null)
            {
                // at least a line that starts with --
                if (this.Line.Length < 3)
                {
                    return false;
                }

                if (buffer[0] == (byte)'-' && buffer[1] == (byte)'-')
                {
                    BuildBoundary(buffer, this.Line.Length);
                    return true;
                }

                return false;
            }

            return IsMatch(buffer, length, this.Boundary, this.Boundary.Length);
        }

        private bool IsLastBoundary()
        {
            byte[] buffer = this.Line.GetBuffer();
            long length = this.Line.Length;

            // we have not found the boundary yet
            if (this.Boundary == null)
            {
                return false;
            }

            return IsMatch(buffer, length, this.LastBoundary, this.LastBoundary.Length);
        }

        /// <summary>
        /// ReadSection
        /// 
        /// Reads a mime section at a time.
        /// </summary>
        /// <param name="section">Section</param>
        /// <returns>Returns true if section is read</returns>

        public bool ReadSection(out MimeSection section)
        {
            section = null;

            if (this.Last)
            {
                return false;
            }

            this.Region.Seek(0, SeekOrigin.Begin);
            this.Region.SetLength(0);

            bool foundCR = false;
            bool CRLF = false;

            do
            {
                int b = this.Stream.ReadByte();

                if (b == -1)
                {
                    return false;
                }
                else
                {
                    if (b == '\r')
                    {
                        if (foundCR) this.Line.WriteByte((byte)'\r');
                        foundCR = true;
                    }
                    else if (foundCR)
                    {
                        if (b == '\n')
                        {
                            ++this.LineCount;
                            bool found = IsBoundary();

                            if (!found)
                            {
                                this.Last = IsLastBoundary();
                            }

                            found = found || this.Last;

                            if (found)
                            {
                                ++this.Section;

                                if (this.Section == 0)
                                {
                                    this.Region = new MemoryStream();
                                }
                                else
                                {
                                    this.Region.Seek(0, SeekOrigin.Begin);
                                    section = new MimeSection(this.Region);
                                    this.Region = new MemoryStream();
                                }

                                CRLF = false;
                            }
                            else
                            {
                                if (CRLF)
                                {
                                    this.Region.WriteByte((byte)'\r');
                                    this.Region.WriteByte((byte)'\n');
                                }

                                byte[] tmp = this.Line.ToArray();
                                this.Region.Write(tmp, 0, tmp.Length);

                                CRLF = true;
                            }

                            this.Line.Seek(0, SeekOrigin.Begin);
                            this.Line.SetLength(0);

                            if (section != null) return true;

                            foundCR = false;
                        }
                        else
                        {
                            this.Line.WriteByte((byte)'\r');
                            if (b != '\r')
                            {
                                this.Line.WriteByte((byte)b);
                                foundCR = false;
                            }
                        }
                    }
                    else
                    {
                        this.Line.WriteByte((byte)b);
                    }
                }

            } while (true);

        }
    }
}
